package model;

import java.util.LinkedList;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
 * @author kagioglu
 */
public class StrawberryClock implements Clock
{
    private final Collection< ClockListener > listenerCollection;
    private Timer timer;
    private long msecsPerTick;
    
    public StrawberryClock( long msecs ) {
        this.listenerCollection = new LinkedList< ClockListener >();
        this.initializeTimer();
        msecsPerTick = msecs;
    }
    
    private void initializeTimer()
    {
        this.timer = new Timer( "i am the strawberry clock" );
    }
    
    private void initializeTask()
    {
        class StrawberryTask extends TimerTask
        {
            private final Collection< ClockListener > sblisteners;
            
            public StrawberryTask( Collection< ClockListener > sblisteners ) {
                this.sblisteners = sblisteners;
            }
            
            public void run()
            {
                synchronized ( this.sblisteners )
                {
                    for ( ClockListener listener : sblisteners )
                    {
                        listener.tick();
                    }
                }
            }
        }
        
        this.timer.scheduleAtFixedRate( new StrawberryTask( this.listenerCollection ),
                                        msecsPerTick, msecsPerTick );
    }
    
    public void addListener( ClockListener listener )
    {
        synchronized ( this.listenerCollection )
        {
            this.listenerCollection.add( listener );
        }
    }
    
    public void removeListener( ClockListener listener )
    {
        synchronized ( this.listenerCollection )
        {
            this.listenerCollection.remove( listener );
        }
    }
    
    public void start()
    {
        this.timer.cancel();
        this.initializeTimer();
        this.initializeTask();
    }
    
    public void stop()
    {
        this.timer.cancel();
    }
}
